<template>
  <div class="global-monitor pd-20 h-100P flex-column">
    <div class="legend flex align-center fz-20 mg-bottom-20">
      <span class="mg-right-20">全局地图</span>
      <svg-icon icon-class="videotape" class="primary-text fz-18 mg-right-6"></svg-icon>
      <span class="mg-right-20 fz-14">未处理事件</span>
      <svg-icon icon-class="robot" class="fz-22 mg-right-6"></svg-icon>
      <span class="mg-right-20 fz-14">已在线的安防机器人</span>
      <svg-icon icon-class="webcam" class="fz-22 mg-right-6"></svg-icon>
      <span class="mg-right-20 fz-14">已在线的安防摄像头</span>
    </div>
    <div class="flex-sub flex ">
      <div class="map h-100P flex-sub rela" v-loading="mapLoading">
        <amap-cmp :zoom.sync="map.zoom" ref="myMap" :center="map.center">
          <amap-marker
            v-for="device in showDeviceLIst"
            :position="[device.locationVo.longitude, device.locationVo.latitude]"
            :key="device.id"
            :offset="[0, 0]"
            anchor="center"
          >
            <div>
              <img
                class="map-icon"
                v-if="device.productVo.icon"
                :src="device.productVo.icon"
                @click="handleShowInfoWindow(device,true)"
              />
            </div>
          </amap-marker>

          <amap-polygon
            :fillOpacity="fillOpacity"
            strokeColor="#339df1"
            fillColor="#0084ee"
            v-for="item in areaList"
            :key="item.id"
            :path="item.path"
          />

          <AmapInfoWindow
            v-if="activateDevice"
            :position="[activateDevice.locationVo.longitude, activateDevice.locationVo.latitude]"
            :offset="[0,-15]"
            :visible="activateDevice.showInfoWindow"
            auto-move
            is-custom
          >
            <div class="amap-info-window bg-white pd-10 flex-column">
              <div class="head justify-between align-center">
                <div>
                  {{ activateDevice.remarkName }}
                </div>
                <i
                  class="el-icon-close fw-20"
                  @click="handleShowInfoWindow(activateDevice,false)"
                ></i>
              </div>
              <div class="mg-top-6 body flex-sub bg-gray "></div>
            </div>
          </AmapInfoWindow>
        </amap-cmp>

        <div class="abso err-tip" v-if="!isShowRobot">
          机器人信息获取异常或者设备经纬度获取失败，请检查机器人是否正常
        </div>
      </div>
      <!-- <div class="dashboard"></div> -->
    </div>
  </div>
</template>

<script>
import AmapCmp from '@amap/amap-vue/lib/amap'
import AmapMarker from '@amap/amap-vue/lib/marker'
import { fakeRobotData } from './fakeRobot.js'
import AmapInfoWindow from '@amap/amap-vue/lib/info-window'
import { loadAmap, loadPlugins } from '@amap/amap-vue'
import AmapPolygon from '@amap/amap-vue/lib/polygon'
import {
  apiFindDevicesPagePyParam,
  apiGetAllArea,
  apiGetRobotBaseMsg,
  apiFindDeviceById,
} from '@/views/monitor/global/api'

export default {
  name: 'GlobalMonitor',
  components: { AmapCmp, AmapMarker, AmapInfoWindow, AmapPolygon },

  data() {
    return {
      mapLoading: false,
      map: {
        zoom: 20,
        center: [113.598276, 22.365508],
      },
      fillOpacity: 0.15,
      deviceList: [],
      activateDevice: null,
      areaList: [],
      isShowRobot: true,
      robotMarketInfo: {},
      robotFakeInfo: {},
      timer: null,
      robotRobotCount: 0,
      robotTimer: null,
      pathRobot: {
        id: `${new Date().getTime()}_path_Robot`,
        locationVo: { longitude: 113.5979, latitude: 22.365575 },
        productVo: { icon: require('./img/robot.png') },
      },
    }
  },
  created() {
    this.initMap()
    this.initData()
    this.handleGetAllArea()
    this.simulateRobot()
    // this.timer = setInterval(() => {
    //   this.handleGetRobotInfo()
    // }, 3000)

    this.robotTimer = setInterval(() => {
      this.simulateRobot()
    }, 5000)
  },

  beforeDestroy() {
    clearInterval(this.timer)
    clearInterval(this.robotTimer)
  },
  mounted() {
    setTimeout(() => {
      const walkOption = {
        map: this.$refs.myMap.$map,
        hideMarkers: false,
        isOutline: true,
        outlineColor: '#ffeeee',
        autoFitView: true,
      }

      // const walking = new AMap.Walking(walkOption)
      const walking = new this.$refs.myMap.$amap.context.AMap.Walking(walkOption)
      const { longitude, latitude } = this.pathRobot.locationVo
      walking.search([longitude, latitude], [113.59883, 22.365592], function (status, result) {
        if (status === 'complete') {
          console.log('步行路线数据查询成功', result)
        } else {
          console.log('步行路线数据查询失败' + result)
        }
      })
    }, 4000)
    this.print()
  },
  computed: {
    showDeviceLIst() {
      if (this.isShowRobot && this.robotMarketInfo.locationVo) {
        return [...this.deviceList, this.robotMarketInfo, this.pathRobot, this.robotFakeInfo]
      }

      return [...this.deviceList, this.pathRobot, this.robotFakeInfo]
    },
  },
  methods: {
    async initMap() {
      await loadAmap()
      // 插件
      await loadPlugins(['MoveAnimation'])
    },
    async initData() {
      this.findDevicesPagePyParam()
    },
    async findDevicesPagePyParam() {
      this.mapLoading = true
      const res = await apiFindDevicesPagePyParam()

      this.deviceList = res
        .filter(device => {
          return !!device.locationVo && device.productVo && device.productVo.icon
        })
        .map(device => {
          // device.icon = 'webcam'
          device.showInfoWindow = false
          return device
        })

      this.mapLoading = false
    },
    handleShowInfoWindow(device, show) {
      device.showInfoWindow = show
      this.activateDevice = device
    },
    async handleGetAllArea() {
      const res = await apiGetAllArea()

      const path = []
      res.forEach(item => {
        path.push({
          id: item.id,
          path: item.locationVos.map(local => [local.longitude, local.latitude]),
        })
      })
      this.areaList = path
    },
    // 绘制路径
    print() {
      // eslint-disable-next-line no-undef
      AMapUI.load(['ui/misc/PathSimplifier'], PathSimplifier => {
        if (!PathSimplifier.supportCanvas) {
          this.alert('当前环境不支持 Canvas！')
          return
        }
        // 创建组件实例
        var pathSimplifierIns = new PathSimplifier({
          map: this.map,
          zIndex: 100, // 图层叠加顺序
          data: fakeRobotData, // 巡航路径
          // 获取巡航路径中的路径坐标数组
          getPath: (pathData, pathIndex) => {
            return pathData.path
          },
        })
        // 创建巡航器
        var pathNavigator = pathSimplifierIns.createPathNavigator(0, {
          loop: true, // 是否循环
          speed: 2000, // 速度(km/h)
        })
        pathNavigator.start()
      })
    },
    simulateRobot() {
      this.robotFakeInfo = {
        id: `${new Date().getTime()}_vRobot`,
        locationVo: fakeRobotData[this.robotRobotCount],
        productVo: { icon: require('./img/robot.png') },
      }
      this.robotRobotCount =
        this.robotRobotCount === fakeRobotData.length - 1 ? 0 : this.robotRobotCount + 1
    },

    async handleGetRobotInfo() {
      const deviceInfo = await apiFindDeviceById({ deviceId: '1418402338774876161' })

      if (deviceInfo && deviceInfo.online) {
        const robotInfo = await apiGetRobotBaseMsg({ RobotID: 'DADAO_ZH_002' })

        if (
          robotInfo.code === '200' &&
          parseFloat(robotInfo.data.latitude) &&
          parseFloat(robotInfo.data.longitude)
        ) {
          // eslint-disable-next-line no-undef
          AMap.convertFrom(
            [parseFloat(robotInfo.data.longitude), parseFloat(robotInfo.data.latitude)],
            'gps',
            (status, result) => {
              if (result.info === 'ok') {
                this.robotMarketInfo = {
                  id: new Date().getTime() + '_custom',
                  productVo: { icon: require('./img/robot.png') },
                  locationVo: {
                    longitude: result.locations[0].lng,
                    latitude: result.locations[0].lat,
                  },
                }

                // 为了调试定位机器人到地图的中心
                // this.map.center = [result.locations[0].lng, result.locations[0].lat]
                this.isShowRobot = true
              }
            }
          )
        } else {
          this.isShowRobot = false
        }
      }
    },
  },
}
</script>

<style scoped lang="scss">
.global-monitor {
  .map {
    padding: vw(10px);
    border: 1px #999 solid;
  }

  .dashboard {
    width: calc(33% - #{vw(20px)});
    margin-left: vw(20px);
    border: 1px #999 solid;
  }

  .amap-info-window {
    width: 200px;
    height: 150px;

    .el-icon-close {
      cursor: pointer;
    }
  }
}

::v-deep {
  .amap-logo {
    display: none !important;
  }

  .amap-copyright {
    display: none !important;
  }
}

.map-icon {
  width: vw(20px);
  height: vw(20px);
}

.err-tip {
  top: vh(20px);
  left: vw(20px);
  font-size: vw(13px);
  color: #d12d1f;
}
</style>
